package model.factories.misc;

import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;
import model.Interpreter;
import model.SyntaxErrorException;
import model.commands.Command;
import model.commands.misc.SaveCommand;
import model.factories.CommandFactory;


/**
 * A factory used to build SaveCommand objects.
 * 
 * @author Erick Gonzalez
 */
public class SaveCommandFactory extends CommandFactory {


    private final Pattern mySavePattern = Pattern.
            compile(getInterpreter().getLanguage().getString("SaveCommandPattern"));

    /**
     * 
     * @param interpreter an interpreter
     */
    public SaveCommandFactory (Interpreter interpreter) {
        super(interpreter);
    }

    @Override
    public Command createCommand (Scanner commandReader,
                                  Map<String, Integer> variables) throws SyntaxErrorException {
        // read SAVE keyword
        commandReader.next();
        // read opening bracket
        commandReader.next();

        StringBuilder fileNameBuilder = new StringBuilder();
        while (!commandReader.hasNext("]")) {
            fileNameBuilder.append(commandReader.next() + " ");
        }
        commandReader.next();

        Interpreter interpreter = getInterpreter();

        return new SaveCommand(fileNameBuilder.toString().trim(), interpreter.getCommandHistory());
    }

    @Override
    public Pattern patternToMatch () {
        return mySavePattern;
    }

}
